from django.conf import settings
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response

from .models import Nav, Banner
from .serializers import NavSerializer, BannerSerializer
from django.core.cache import cache
from django.core.files.storage import default_storage


# Create your views here.
# 1.定义首页接口
class homeViewSet(viewsets.ModelViewSet):
    @action(methods=['get'], detail=False)
    def nav(self, request):
        # 首先读取缓存
        key = 'nav'
        navs = cache.get(key)
        if navs is None:
            navs = Nav.objects.filter(is_show=1, position=0)
            serializer = NavSerializer(navs, many=True)
            cache.set(key, serializer.data, 60 * 60 * 24)
            return Response({
                'code': 200,
                'message': 'success',
                'data': serializer.data
            })
        else:
            print("读取缓存数据：", navs)
            return Response({
                'code': 200,
                'message': 'success',
                'data': navs
            })

    @action(methods=['get'], detail=False)
    def foot(self, request):
        navs = Nav.objects.filter(is_show=1, position=1)
        serializer = NavSerializer(navs, many=True)
        return Response({
            'code': 200,
            'message': 'success',
            'data': serializer.data
        })

    @action(methods=['POST'], detail=False)
    def upload_file(self, request):
        file = request.FILES.get('file')
        if file.size > 1024 * 1024 * 20:
            return Response({
                'code': 400,
                'message': '文件过大',
                'data': []
            })
        if file.content_type not in ['image/jpeg', 'image/png']:
            return Response({
                'code': 400,
                'message': '文件格式错误',
                'data': []
            })
        uploadFile = default_storage.save('banner/'+file.name, file)
        url = default_storage.url(uploadFile)
        return Response({
            'code': 200,
            'message': 'success',
            'data': {"imgUrl":url}
        })

    @action(methods=['get'], detail=False)
    def banner(self, request):
        banners = Banner.objects.filter(is_show=1)
        serializer = BannerSerializer(banners, many=True)
        for item in serializer.data:
            item["image"] = settings.FILE_HOST + item["image"]
        return Response({
            'code': 200,
            'message': 'success',
            'data': serializer.data
        })
# 在返回图片数据的时候会自动补全路径域名信息，但是注意如果数据库图片字段是char类型，就不会自动补全域名信息，必须是uploadFile字段才会补全
class BannerListViewSet(ListAPIView):
    queryset = Banner.objects.filter(is_show=1)
    serializer_class = BannerSerializer
